/*
 * @Author: Suo-Yuheng syh15399227325@163.com
 * @Date: 2025-08-30 22:45:55
 * @LastEditors: Suo-Yuheng syh15399227325@163.com
 * @LastEditTime: 2025-08-30 23:15:37
 * @FilePath: /0830/tickets/mythread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<cstdio>
#include<vector>
#include<string>

using namespace std;
#define NUM 6


class threadData
{
public:
    threadData(int number)
    {
        _threadname = "thread-" + to_string(number);
    }

    // ~threadData();

    string _threadname;
};

int tickets = 1000; // 用多线程， 模拟一轮抢票、其实就是 一堆线程，对 tickets 做 - - 操作


void* getTickets(void* args)
{
    threadData* td = static_cast<threadData*>(args);
    const char* name = td->_threadname.c_str();

    while(true)
    {
        if(tickets > 0)
        {
            usleep(1000);
            printf("who=%s, get a ticket: %d\n", name, tickets);
            tickets--;
        }
        else{
            break;
        }
    }
    
    printf("%s ... quit\n", name);
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    vector<threadData*> thread_datas;
    for (size_t i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData(i);
        thread_datas.push_back(td);
        pthread_create(&tid, nullptr, getTickets, thread_datas[i-1]);
        tids.push_back(tid);
    }
    


    for (auto thread : tids)
    {
        pthread_join(thread, nullptr);
    }
    for (auto td : thread_datas)
    {
        delete td;
    }
}


